require 'libluartk'
local requests = require("requests")

-- 定义翻译函数
-- @param text 待翻译的文本
-- @param fromLang 源语言 (例如: "auto", "zh", "en")
-- @param toLang 目标语言 (例如: "en", "zh", "ja")
-- @return 翻译结果字符串或 nil + 错误信息
function xiaoniu_translate_text(text, fromLang, toLang)
	local ini=os.getenv('USERPROFILE') .. '/.ssh/xiaoniu.ini'
	local appid=rtk.getini('fanyi','appid',ini)
	local key=rtk.getini('fanyi','key',ini)
	function make_auth_str(req,apikey)
		local arr={}
		rtk.table_each(req,function(k,v)
			table.insert(arr,{k,v})
		end)
		table.sort(arr,function(a,b) return a[1]<b[1] end)
		rtk.table_ieach(arr,function(_,v)
			arr[_]=v[1] .. '=' .. v[2]
		end)
		local hdr=string.format('apikey=%s&%s',apikey or key,table.concat(arr,'&'))
		--printf('H1="%s"',hdr)
		return rtk.string_toHex(rtk.string_hash(hdr,'MD5'))
	end

    local api_url = "https://api.niutrans.com/v2/text/translate"
    local data = {
        from = fromLang,
        to = toLang,
        srcText = text,
		appId = appid,
		timestamp=tostring(os.time())
    }
	data.authStr=make_auth_str(data,key)
    -- 4. 发送 POST 请求
	--tprint('Request=',data)
	local headers = {['Content-Type'] = 'application/json'}
    local response = requests.post(api_url,{data=data,headers=headers})
	--tprint(response)
	if response.status_code~=200 then
		return nil,response.status
	end
	response=response.json()
	--tprint(response)
	if response.errorCode then
		return nil,response.errorMsg
	end
	return response.tgtText
end

--tprint{xiaoniu_translate_text(io.read('*a'),arg[1],arg[2])}

function baidu_translate_text(text, src_lang, dest_lang)
	local ini=os.getenv('USERPROFILE') .. '/.ssh/baidu.ini'
	local appid=rtk.getini('fanyi','appid',ini)
	local secret_key=rtk.getini('fanyi','key',ini)
	local url='https://fanyi-api.baidu.com/api/trans/vip/translate'
    local salt = tostring(math.random(32768, 65536))
    local code = appid .. text .. salt .. secret_key
	local encoder = require('cgilua.urlcode')
    local sign = rtk.string_toHex(rtk.string_hash(code),'md5')
    local data = {
        q=encoder.escape(text),
        from= src_lang,
        to= dest_lang,
        appid= appid,
        salt= salt,
        sign= sign
    }
	local headers = {['Content-Type'] = 'application/x-www-form-urlencoded'}
	local ret=requests.post(url,{params=data,headers=headers})
	rtk.tprint(ret.json())
end

--baidu_translate_text('你好，这里是中央人民广播电台','zh','ru')